package com.itheima.common;

import com.itheima.common.R;
import java.sql.SQLIntegrityConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * 全局异常处理器
 */
@Slf4j
@ControllerAdvice(annotations = {RestController.class, Controller.class}) //拦截加了该注解的类
@ResponseBody     //响应json数据
public class GlobalExceptionHandler {

    /**
     * 异常处理方法
     *
     * @param ex
     * @return
     */
    //拦截指定异常的处理方案
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {

        log.error(ex.getMessage()); //打印错误
        //判断 是否包含    Duplicate entry 'zhangsan' for key 'idx_username'
        if (ex.getMessage().contains("Duplicate entry")) {
            String[] split = ex.getMessage().split(" "); //按照空格切割
            String msg = split[2];  //获取第三个元素
            return R.error(msg + " 已存在");
        }

        return R.error("未知错误");
    }


    /**
     * 表关联删除
     * @param ex
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex) {
        log.error(ex.getMessage()); //打印错误
        return R.error(ex.getMessage());
    }
}
